using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Principal;
using System.Text;
using Update.Utils.Interfaces;

namespace Update.Utils.System
{
    /// <summary>
    /// 系统辅助类
    /// </summary>
    public class SystemHelper : ISystemHelper
    {
        /// <summary>
        /// 判断是否以管理员权限运行
        /// </summary>
        /// <returns>是否以管理员权限运行</returns>
        public bool IsRunAsAdministrator()
        {
            try
            {
                WindowsIdentity identity = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                return principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 以管理员权限重启程序
        /// </summary>
        /// <param name="args">命令行参数</param>
        /// <returns>是否成功启动</returns>
        public bool RestartAsAdministrator(string args = "")
        {
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.UseShellExecute = true;
                startInfo.WorkingDirectory = Environment.CurrentDirectory;
                startInfo.FileName = Process.GetCurrentProcess().MainModule.FileName;
                startInfo.Verb = "runas";
                
                if (!string.IsNullOrEmpty(args))
                {
                    startInfo.Arguments = args;
                }
                
                Process.Start(startInfo);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取应用程序版本
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>版本号</returns>
        public string GetFileVersion(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(filePath);
                    return versionInfo.FileVersion;
                }
            }
            catch
            {
                // 忽略错误
            }
            
            return "";
        }

        /// <summary>
        /// 获取正在运行的进程列表
        /// </summary>
        /// <returns>进程名称列表</returns>
        public string[] GetRunningProcesses()
        {
            try
            {
                Process[] processes = Process.GetProcesses();
                string[] processNames = new string[processes.Length];
                
                for (int i = 0; i < processes.Length; i++)
                {
                    processNames[i] = processes[i].ProcessName;
                }
                
                return processNames;
            }
            catch
            {
                return new string[0];
            }
        }

        /// <summary>
        /// 通过进程名结束进程
        /// </summary>
        /// <param name="processName">进程名</param>
        /// <returns>是否成功</returns>
        public bool KillProcessByName(string processName)
        {
            try
            {
                Process[] processes = Process.GetProcessesByName(processName);
                
                if (processes.Length == 0)
                {
                    return false;
                }
                
                foreach (Process process in processes)
                {
                    process.Kill();
                    process.WaitForExit(2000);
                }
                
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 通过进程ID结束进程
        /// </summary>
        /// <param name="processId">进程ID</param>
        /// <returns>是否成功</returns>
        public bool KillProcessById(int processId)
        {
            try
            {
                Process process = Process.GetProcessById(processId);
                process.Kill();
                process.WaitForExit(2000);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取占用文件的进程ID
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>进程ID数组</returns>
        public int[] GetProcessesLockingFile(string filePath)
        {
            // 注意：此功能需要额外的System.Management引用
            // 为了避免依赖问题，这里返回空数组
            return new int[0];
        }

        /// <summary>
        /// 获取进程可执行文件路径
        /// </summary>
        /// <param name="processId">进程ID</param>
        /// <returns>可执行文件路径</returns>
        private string GetProcessExecutablePath(int processId)
        {
            try
            {
                Process process = Process.GetProcessById(processId);
                return process.MainModule.FileName;
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取系统信息
        /// </summary>
        /// <returns>系统信息字符串</returns>
        public string GetSystemInfo()
        {
            StringBuilder sb = new StringBuilder();
            
            try
            {
                // 操作系统信息
                sb.AppendLine("操作系统信息:");
                sb.AppendLine($"  操作系统: {Environment.OSVersion}");
                sb.AppendLine($"  系统目录: {Environment.SystemDirectory}");
                sb.AppendLine($"  处理器数量: {Environment.ProcessorCount}");
                sb.AppendLine($"  系统已运行时间: {GetSystemUptime()}");
                
                // .NET运行时信息
                sb.AppendLine("\n.NET运行时信息:");
                sb.AppendLine($"  .NET版本: {Environment.Version}");
                sb.AppendLine($"  64位操作系统: {Environment.Is64BitOperatingSystem}");
                sb.AppendLine($"  64位进程: {Environment.Is64BitProcess}");
                
                // 内存信息
                sb.AppendLine("\n内存信息:");
                sb.AppendLine($"  工作集: {Environment.WorkingSet / 1024 / 1024} MB");
                
                // 驱动器信息
                sb.AppendLine("\n驱动器信息:");
                foreach (DriveInfo drive in DriveInfo.GetDrives())
                {
                    try
                    {
                        if (drive.IsReady)
                        {
                            sb.AppendLine($"  {drive.Name} ({drive.DriveType}):");
                            sb.AppendLine($"    卷标: {drive.VolumeLabel}");
                            sb.AppendLine($"    文件系统: {drive.DriveFormat}");
                            sb.AppendLine($"    总大小: {drive.TotalSize / 1024 / 1024 / 1024} GB");
                            sb.AppendLine($"    可用空间: {drive.AvailableFreeSpace / 1024 / 1024 / 1024} GB");
                        }
                    }
                    catch
                    {
                        // 忽略驱动器访问错误
                    }
                }
                
                return sb.ToString();
            }
            catch (Exception ex)
            {
                return $"获取系统信息时出错: {ex.Message}";
            }
        }

        /// <summary>
        /// 获取系统运行时间
        /// </summary>
        /// <returns>系统运行时间</returns>
        private string GetSystemUptime()
        {
            try
            {
                using (var uptime = new PerformanceCounter("System", "System Up Time"))
                {
                    uptime.NextValue();
                    TimeSpan ts = TimeSpan.FromSeconds(uptime.NextValue());
                    return $"{ts.Days}天 {ts.Hours}小时 {ts.Minutes}分钟 {ts.Seconds}秒";
                }
            }
            catch
            {
                return "无法获取";
            }
        }

        /// <summary>
        /// 创建开机启动项
        /// </summary>
        /// <param name="appName">应用名称</param>
        /// <param name="appPath">应用路径</param>
        /// <returns>是否成功</returns>
        public bool CreateStartupItem(string appName, string appPath)
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
                {
                    key.SetValue(appName, appPath);
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 删除开机启动项
        /// </summary>
        /// <param name="appName">应用名称</param>
        /// <returns>是否成功</returns>
        public bool RemoveStartupItem(string appName)
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
                {
                    if (key.GetValue(appName) != null)
                    {
                        key.DeleteValue(appName);
                    }
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 检查开机启动项是否存在
        /// </summary>
        /// <param name="appName">应用名称</param>
        /// <returns>是否存在</returns>
        public bool IsStartupItemExists(string appName)
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", false))
                {
                    return key.GetValue(appName) != null;
                }
            }
            catch
            {
                return false;
            }
        }
    }
} 